<?php

namespace App\Controller;

use Think\Controller;

class WechatController extends Controller
{
    public function _initialize()
    {
    }

    public function index()
    {
        require_once WEB_PATH.'/Application/Common/Vendor/WechatHelper/WechatPhpSdk/Wechat.class.php';
        require_once WEB_PATH.'/Application/Common/Vendor/WechatHelper/WechatPhpSdk/Utils/Prpcrypt.class.php';
        require_once WEB_PATH.'/Application/Common/Vendor/WechatHelper/WechatPhpSdk/Utils/SHA1.class.php';
        require_once WEB_PATH.'/Application/Common/Vendor/WechatHelper/WechatPhpSdk/Utils/Pkcs7Encoder.class.php';

        $wechat = new \Gaoming13\WechatPhpSdk\Wechat(array(
            'appId' => C('WX.appId'),
            'token' => '5feec52737',
            'encodingAESKey' => 'AtbsKiyVMRF8xvZygFjB1n4p1xB3e0sKFN1iwpOVP1a',
        ));
        $default_msg = "欢迎关注炬力帮，进入<a href='http://www.tasksys.online/taskSys'>任务大厅</a>开始任务";

        // 获取微信消息
        $msg = $wechat->serve();

        $shareUrl = 'http://www.tasksys.online/taskSys/?parentId=';
        // 用户关注微信号后 - 回复用户普通文本消息
        if ('event' == $msg->MsgType && 'subscribe' == $msg->Event) {
            if (!empty($msg->EventKey)) {
                $sceneId = str_replace('qrscene_', '', $msg->EventKey);
                $shareUrl .= $sceneId;
                $this->addUser($sceneId.'', $msg->FromUserName.'');
                $wechat->reply($default_msg);
                exit();
            }
            $wechat->reply($default_msg);
            exit();
        }
        if ('event' == $msg->MsgType && 'SCAN' == $msg->Event) {
            $shareUrl .= $msg->EventKey;
            $this->addUser($msg->EventKey.'', $msg->FromUserName.'');
            $wechat->reply($default_msg);
            exit();
        }
        if ('event' == $msg->MsgType && 'CLICK' == $msg->Event) {
            if (!empty($msg->EventKey)) {
                switch ($msg->EventKey) {
                    case 'kefu':
                        $wechat->reply('联系客服微信号：linhong0703');
                        break;
                    case 'lsgg':
                        $this->sendHistory($msg->FromUserName.'');
                        break;
                    case 'swhz':
                        $wechat->reply("商务合作的联系人：\r\n钟：15012683964\r\n关：13825201894");
                        break;
                }
                exit();
            }
        }
        exit();
    }

    private function addUser($parentId, $openId)
    {
        $sysUserInfoRes = A('Common/WxUser', 'Logic')->getUserInfoById('', $openId);

        //openid未注册的时候，注册号码
        if (D('Res', 'Logic')->isErr($sysUserInfoRes)) {
            $wxLogic = A('App/Wx', 'Logic');
            $api = $wxLogic->getWxApi();
            list($err, $userInfo) = $api->get_user_info($openId, 'zh_CN');

            if (empty($userInfo)) {
                //注册并登陆
                $param = array(
                    'openid' => $openId,
                    'photo' => '',
                    'name' => $openId,
                    'sex' => '',
                );

                //记录推荐人id
                if ($parentId) {
                    $param['parent_id'] = $parentId;
                }

                $addRes = A('Common/WxUser', 'Logic')->addUser($param);

                return false;
            }

            //将微信的用户头像转存到本地服务器
            // $photoUri = $userInfo->headimgurl;
            // $imgBase64 = base64_encode(file_get_contents($photoUri));

            // $imageUri = "/ImgFile/UserHeadPhoto/" . date("Ymd") . "/" . time() . "_" . rand(1111, 9999) . '.jpg';
            // $fileName = WEB_PATH . $imageUri;

            // if (saveImg($imgBase64, $fileName)) {
            //     $photoUri = DOMIAN . $imageUri;
            // }
            //注册并登陆
            $param = array(
                'openid' => $openId,
                // "photo" => $photoUri,
                'name' => $userInfo->nickname,
                'sex' => $userInfo->sex,
            );

            //记录推荐人id
            if ($parentId) {
                $param['parent_id'] = $parentId;
            }
            $addRes = A('Common/WxUser', 'Logic')->addUser($param);
        }
    }

    public function createMenu()
    {
        $wxLogic = A('Wx', 'Logic');
        $api = $wxLogic->getWxApi();
        $api->create_menu('
{
    "button":[
        {   
          "type":"view",
          "name":"任务大厅",
          "url":"http://www.tasksys.online/taskSys"
        },
        {
            "type":"click",
            "name":"历史公告",
            "key":"lsgg"
       },
        {
            "type":"click",
            "name":"商务合作",
            "key":"swhz"
       }
    ]
}');
    }

    public function sendHistory($openid)
    {
        $wxLogic = A('Wx', 'Logic');
        $api = $wxLogic->getWxApi();
        list($error, $total) = $api->get_material_count();
        if ($total->news_count > 0) {
            list($error, $data) = $api->get_materials('news', $total->news_count - 1, 1);
            $api->send($openid, array(
    'type' => 'mpnews',
    'media_id' => reset($data->item)->media_id,
        ));
        }
    }
}
